package userlogic

import (
	"context"
	"time"

	"go-zero-admin/apps/system/cmd/rpc/internal/svc"
	"go-zero-admin/apps/system/cmd/rpc/syspb"
	"go-zero-admin/apps/system/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpUserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpUserLoginLogic {
	return &UpUserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpUserLoginLogic) UpUserLogin(in *syspb.UpUserLoginReq) (*syspb.UpUserLoginResp, error) {
	if in.GetIp() == "" || in.GetUpdateUser() == "" {
		return nil, errors.Wrapf(xerr.NewErrMsg("更新用户登陆信息失败：参数缺失"),
			tool.GetErrMsgFormat("update user login info"), "params is not existed", in)
	}

	// 查询出用户信息
	user, err := l.svcCtx.SysUserModel.FindOne(l.ctx, in.GetId())
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("update user login info"), err, in)
	}
	user.LastLoginIp = in.GetIp()
	user.LastLoginTime = time.Now()
	user.UpdateUser = in.GetUpdateUser()

	// 更新
	err = l.svcCtx.SysUserModel.UpdateEx(l.ctx, nil, user)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("update user login info"), err, in)
	}

	return &syspb.UpUserLoginResp{}, nil
}
